package com.truthbean.jutils.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by TruthBean on 2016-09-02 15:58.
 */
@WebListener
public class UserSessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("创建 session");
        HttpSession session = se.getSession();
        ServletContext context = session.getServletContext();
        Integer onLineCount = (Integer) context.getAttribute("onLineCount");
        if (onLineCount == null) {
            context.setAttribute("onLineCount", 1);
            onLineCount = 1;
        } else {
            onLineCount++;
            context.setAttribute("onLineCount", onLineCount);
        }
        System.out.println(onLineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session 注销");
        ServletContext context = se.getSession().getServletContext();
        Integer onLineCount = (Integer) context.getAttribute("onLineCount");
        if (onLineCount == null) {
            context.setAttribute("onLineCount", 0);
            onLineCount = 0;
        } else {
            onLineCount--;
            context.setAttribute("onLineCount", onLineCount);
        }
        System.out.println(onLineCount);
    }
}
